import requests
import pymysql
from app.conf.config import *

SHOPIFY_API_KEY = config.SHOPIFY_API_KEY
SHOPIFY_API_SECRET = config.SHOPIFY_API_SECRET
SHOPIFY_TOKEN_URL = config.SHOPIFY_TOKEN_URL
# 1. 调用Shopify官方接口获取AccessToken
def fetch_shopify_access_token(shop_domain: str, code: str, scope: str) -> str:
    """根据店铺域名和授权code，获取Shopify AccessToken"""
    token_url = SHOPIFY_TOKEN_URL.format(shop_domain=shop_domain)
    payload = {
        "client_id": SHOPIFY_API_KEY,
        "client_secret": SHOPIFY_API_SECRET,
        "code": code
    }
    try:
        response = requests.get(token_url, json=payload, timeout=10)
        response.raise_for_status()  # 触发HTTP错误（4xx/5xx）
        return response.json()["access_token"]
    except requests.exceptions.RequestException as e:
        raise Exception(f"获取AccessToken失败：{str(e)}")


# 2. 保存/更新用户数据到MySQL
def save_or_update_user(conn, shopify_domain: str, access_token: str, code: str, scope: str):
    """存在则更新，不存在则新增（基于shopify_domain唯一键）"""
    with conn.cursor() as cursor:
        # 先查询是否已存在该店铺记录
        query_sql = "SELECT id FROM shopify_app.users WHERE shop_domain = %s"
        cursor.execute(query_sql, (shopify_domain,))
        user = cursor.fetchone()

        if user:
            # 存在则更新
            update_sql = """
            UPDATE shopify_app.users 
            SET access_token = %s, code = %s, scope = %s, updated_at = CURRENT_TIMESTAMP
            WHERE shop_domain = %s
            """
            cursor.execute(update_sql, (access_token, code, scope, shopify_domain))
        else:
            # 不存在则新增
            insert_sql = """
            INSERT INTO shopify_app.users (shop_domain, access_token, code, scope)
            VALUES (%s, %s, %s, %s)
            """
            cursor.execute(insert_sql, (shopify_domain, access_token, code, scope))
        conn.commit()  # 提交事务


# 3. 删除用户AccessToken（按店铺域名）
def delete_user_access_token(conn, shopify_domain: str) -> bool:
    """删除指定店铺的Token记录"""
    with conn.cursor() as cursor:
        delete_sql = "DELETE FROM shopify_app.users WHERE shop_domain = %s"
        affected_rows = cursor.execute(delete_sql, (shopify_domain,))
        conn.commit()
        return affected_rows > 0  # 有影响行数则返回True


# 4. 回调接口整合流程
def handle_oauth_callback(conn, shop_domain: str, code: str, scope: str) -> dict:
    """完整流程：解析参数→获取Token→保存到MySQL"""
    # 校验必要参数
    if not all([shop_domain, code, scope]):
        raise Exception("缺少必要参数（shop/code/scope）")
    try:
        # 获取AccessToken
        access_token = fetch_shopify_access_token(shop_domain, code)
        # 保存到数据库
        save_or_update_user(conn, shop_domain, access_token, code, scope)
        # 返回结果
        return {
            "status": 1,
            "shopify_domain": shop_domain,
            "access_token": access_token,
            "scope": scope,
            "msg": "Token获取并保存成功"
        }
    except Exception as e:
        return {
            "status": 0,
            "shopify_domain": shop_domain,
            "msg": "Token保存失败"
        }
